﻿using Common;
using IServices.Sys;
using System;
using System.Collections.Generic;
using System.Linq;
using Web.Controllers;
using DTO.ViewModel;
using System.Threading.Tasks;
using DTO.DTO.Sys.Role;
using Common.Utility;
using DTO;
using Common.Property;
using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Web.Areas.Sys.Controllers
{
    public class RoleController : BaseController
    {
        private readonly IRoleService _service;

        public RoleController(IHttpContextAccessor httpContextAccessor, IMapper mapper, IRoleService service) : base(httpContextAccessor, mapper)
        {
            _service = service;
        }

        // GET: Sys/Role
        public IActionResult Index()
        {
            ViewBag.Status = EnumHelper.GetNVCFromEnumValue(typeof(E_Status));
            return View();
        }

        public async Task<ResultList> List(RoleQueryDTO dto)
        {
            var result = await _service.GetRolePageList(dto);
            var map = _mapper.Map<List<RoleListDTO>>(result.Item1);
            return ResultList.Success(count: result.Item2, data: map);
        }

        public async Task<Result> Del(string id)
        {
            return await _service.DeleteRole(id, OperatorInfo) ? Result.Success("删除成功") : Result.Failed(-1, "删除失败");
        }

        public async Task<Result> Delist(List<string> ids)
        {
            return await _service.DeleteBatchRole(ids, OperatorInfo) ? Result.Success("删除成功") : Result.Failed(-1, "删除失败");
        }

        public async Task<IActionResult> Edit(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                var initModel = new RoleDetailDTO();
                return View(initModel);
            }
            else
            {
                var model = await _service.GetRoleById(id);
                var modelDTO = _mapper.Map<RoleDetailDTO>(model);
                return View(modelDTO);
            }
        }

        public async Task<Result> Save(RoleDetailDTO model)
        {
            return await _service.SaveRole(model, OperatorInfo);
        }

        public async Task<IActionResult> GetJson()
        {
            var list = await _service.GetRoleList(new RoleQueryDTO { Status = (int)E_Status.Enabled });

            var tree = new List<TreeModel>
            {
                new TreeModel
                {
                    PId = "-1",
                    Id = "0",
                    Name = "所有角色",
                    Open = true
                }
            };

            tree.AddRange(list.Select(item => new TreeModel
            {
                PId = "0",
                Id = item.Id,
                Name = item.Name,
                Open = true
            }));

            return Json(tree);
        }
    }
}